<template>
    <div id="taskDistribution-but-container" class="but-container">
        <div class="but" id="taskDistribution-button-group">
            <el-button plain @click="$router.go(-1)" id="taskDistribution-cancel-button">取消</el-button>
            <el-button type="primary" @click="subClick" id="taskDistribution-add-button">新增</el-button>
        </div>
    </div>
    <div class="form-container" id="taskDistribution-form-container">
        <el-form
            id="taskDistribution-rule-form"
            ref="ruleFormRef"
            class="task-divide"
            :model="divide"
            :rules="rules"
            label-width="auto"
            :size="formSize"
        >
            <el-form-item id="taskDistribution-issued-form-item" label="下发人员：" prop="issued" style="width: 90%;" >
                <el-autocomplete
                  ref="autoCompleteRef"
                  id="taskDistribution-autocomplete-issued"
                  v-model="divide.issued"
                  :fetch-suggestions="querySearchAsync"
                  @select="handleSelect"
                  placeholder="请选择用户名称"
                  @input="handleIssuedChange"
                >
                <template #append >
                    <el-button id="taskDistribution-search-button" class="custom-button" style="background-color: #413d3d; font-size: 16px;color: #ddd;" @click="search" >
                      <el-icon style="margin-right: 5px;"><Search /></el-icon>
                      <samp>搜索</samp>
                    </el-button>
                </template>
                </el-autocomplete>
            </el-form-item>
            <el-form-item id="taskDistribution-title-form-item" label="任务名称：" prop="title" style="width: 90%;">
                <el-input 
                    id="taskDistribution-title-input"
                    v-model="divide.title"
                    placeholder="请输入内容"
                />
            </el-form-item>
            <el-form-item id="taskDistribution-content-form-item" label="任务描述："  prop="content">
                <el-input
                    id="taskDistribution-content-input"
                    v-model="divide.content"
                    type="textarea"
                    placeholder="请输入内容"
                />
            </el-form-item>
            <el-form-item id="taskDistribution-require-form-item" label="任务要求："  prop="require">
                <el-input
                    id="taskDistribution-require-input"
                    v-model="divide.require"
                    type="textarea"
                    placeholder="请输入内容"
                />

            </el-form-item>
            <el-form-item id="taskDistribution-date-range-form-item" label="起止时间：" prop="dateRange" style="width: 100%;" >
              <el-date-picker
                id="taskDistribution-date-range-picker"
                v-model="divide.dateRange"
                type="datetimerange"

                range-separator="至"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
                format="YYYY/MM/DD hh:mm:ss"
                value-format="x"
                placement="bottom"
              />
            </el-form-item>
            <!-- actio上传服务器的地址 -->
            <el-form-item id="taskDistribution-file-form-item" label="附件：" required>
                <el-upload
                  id="taskDistribution-file-upload"
                  ref="upload"
                  accept=".docx,.txt,.xlsx,.ppt,.pptx,.doc"
                  v-model:file-list="fileList"
                  :on-change="fileUpload"
                  :on-exceed="handleExceed"
                  :auto-upload="false"
                  :limit="1"
                  :before-remove="beforeRemove"
                  :picker-options="pickerOptions"
                >
                  <el-button id="taskDistribution-file-upload-button" type="primary" plain>
                    <el-icon style="font-size: 15px;margin-right: 5px;"><Upload /></el-icon>上传
                  </el-button>
                  <template #tip>
                      <div id="taskDistribution-file-upload-div">
                          <samp id="taskDistribution-file-upload-buttotext" style="font-size: 15px;color:#999;">支持doc格式附件,附件大小不能超过4M</samp>
                      </div>
                  </template>
                </el-upload>
            </el-form-item>
        </el-form>
    </div>
</template>

<script setup>
import { ref ,onMounted,watch,computed} from 'vue'
import { Search } from '@element-plus/icons-vue'
import { ElMessage , ElMessageBox , genFileId} from 'element-plus';
import {useTaskDistributionStore} from "@/store/taskDistribution"

const formSize = ref('large')
const autoCompleteRef =ref(null)
const taskDistributionStore = useTaskDistributionStore()


const divide = ref({
  dateRange: [],
  issued:'',
  userId:'',
  appointorId:'',
  workStatusId: 0,
  priorityId: 0,
  attachmentsId:'',
  title:'',
  content:'',
  require:'',
  createTime:'',
  updateTime:'',
  endTime:'',
  deletionState: 0,
  file:'',
})


const userInfo = JSON.parse(localStorage.getItem('userInfo')).data.userId


const ruleFormRef = ref(null)
const rules = ref({
  issued: [
    { required: true, message: '请选择下发人员', trigger: 'change' },
  ],
  title: [
    { required: true, message: '请输入任务名称', trigger: 'blur' },
    { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  content: [
    { required: true, message: '请输入任务描述', trigger: 'blur' },
  ],
  require: [
    { required: true, message: '请输入任务要求', trigger: 'blur' },
  ],
  dateRange: [
    { required: true, message: '请选择起止时间', trigger: 'change' },
  ]
})

//文件上传
const upload = ref(null)
const handleExceed = (files) => {
  upload.value.clearFiles()
  const file = files[0]
  file.uid = genFileId()
  upload.value.handleStart(file)
}
//文件变化
const fileList=ref([])
const fileUpload=(uploadFile)=>{
  if (uploadFile.size / 1024 / 1024 > 4) {
    ElMessage.warning('文件大小不能超过 4MB!')
    fileList.value=[]
    return false
  }
  divide.value.file = uploadFile.raw 
}

//删除文件后
const beforeRemove = async (uploadFile) => {
  try {
  await ElMessageBox.confirm(`是否删除 ${uploadFile.name} ?`);
    divide.value.file = null; // 将文件设置为空
    return true;
  } catch {
    return false;
  }
}


//新增按钮
const subClick = () => {
  const issuedValueExists = links.value.some(item => item.value === divide.value.issued);
  const dateRange = divide.value.dateRange
  if(!issuedValueExists){
    ElMessage.warning("请选择正确的下发人员！")
    return;
  }
  if(divide.value.issued == ""){
    ElMessage.warning("请选择正确的下发人员！")
    return;
  }
  if(divide.value.userId === "" || divide.value.userId == null){
    ElMessage.warning("请选择正确的下发人员！")
    return;
  }
  if(divide.value.title === ""){
    ElMessage.warning("请完善任务名称！")
    return;
  }
  if(divide.value.require === ""){
    ElMessage.warning("请完善任务描述！")
    return;
  }
  if(divide.value.content === ""){
    ElMessage.warning("请完善任务要求！")
    return;
  }
  if(dateRange === null || (Array.isArray(dateRange) && dateRange.length === 0)){
    ElMessage.warning("请选择截止时间！")
    return;
  }
  if(divide.value.file === null || divide.value.file === ""){
    ElMessage.warning("请上传文件！")
    return;
  }
  if(dateRange && dateRange.length === 2){
    divide.value.createTime = dateRange[0]
    divide.value.endTime = dateRange[1]
  }
  divide.value.appointorId = userInfo
  // divide.value.updateTime = divide.value.createTime
  divide.value.updateTime = Date.now()
  taskDistributionStore.taskAssignment(divide.value)
  
}


//搜索按钮
const search = async() =>{
  const userObjs = await taskDistributionStore.getUsername({name:divide.value.issued})
  links.value = userObjs
  autoCompleteRef.value.focus()
}

const handleIssuedChange = async (event) => {
  const newValue = event
  if (newValue === "") {
    const userObjs = await taskDistributionStore.getUsername();
    links.value = userObjs;
  } else {
    const userObjs = await taskDistributionStore.getUsername({ name: newValue });
    links.value = userObjs;
  }
}

//监听下发人员输入框
// watch(divide.value,async (newValue) => {
//   if(newValue.issued == "" || newValue.issued == null){
//     const userObjs = await taskDistributionStore.getUsername()
//     links.value = userObjs
//     divide.value.userId = ""
//   }
//   if(newValue.issued){
//     const userObjs = await taskDistributionStore.getUsername({name:divide.value.issued})
//     links.value = userObjs
//   }
// },{ deep: true })



const links = ref([])

let timeout
const querySearchAsync = (queryString, cb) => {
  const results = queryString ? links.value.filter(createFilter(queryString)) : links.value

  clearTimeout(timeout)
  timeout = setTimeout(() => {
    cb(results)
  }, 100 * Math.random())
}

const createFilter = (queryString) => {
  return (restaurant) => {
    return (
      restaurant.value.toLowerCase().includes(queryString.toLowerCase()) == true
    )
  }
}

//根据用户选择得到用户id
const handleSelect = (item) => {
  divide.value.userId = item.userId
}

onMounted(async() => {  
  const userObjs = await taskDistributionStore.getUsername()
  links.value = userObjs
})

</script>




<style lang="less" scoped>
.form-container {
    display: flex;
    justify-content: center;
    margin-top: 5%;
}
    
.custom-button {
  border-radius: 0 !important;
  .el-button__icon {
    vertical-align: middle; 
  }
}

.task-divide {
    width:40%;
}

.but-container {
  display: flex; 
  justify-content: flex-end;
  align-items: center; 
}


.but {
    display: flex;
    gap: 10px; 
}


@media (max-width:1300px) {
    .task-divide {
        width: 50%; 
    }
 
    .but {
        margin-left: 10%; 
    }
}

@media (max-width: 992px) {
    .task-divide {
        width: 75%; /* 在平板上占据更大宽度 */
    }
 
    .but {
        margin-left: 10%; /* 在平板上减少左边距 */
    }
}
    
@media (max-width: 600px) {
    .task-divide {
      width:100%;
    }
}

</style>


<style>
@media (max-width: 646px) {
  .el-picker-panel__footer {
    text-align: center !important;
  }
  .el-date-range-picker__time-header{
    display: table-cell !important;
  }
  /* .el-date-range-picker__time-picker-wrap{
    display: contents !important;
  } */
  /* .el-date-range-picker .el-picker-panel__content{
    display: none !important;
  } */
  .el-date-range-picker .el-picker-panel__body{
    min-width: 375px !important;
    width: 375px !important;
  }
  .el-date-range-picker__header div {
    font-size: 12px !important;
  }
  .el-date-range-picker__content{
    padding: 0 !important;
  }
  .el-date-range-picker{
    width: 375px !important;
  }
  .el-icon svg{
    display: none !important;
  }
  .el-date-range-picker__editors-wrap {
    display: inline !important;
  }
  .el-date-range-picker__time-picker-wrap{
    padding: 0 18px !important;
  }

}
</style>